package redis;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @Author: admin
 * @Description:
 * @Date: 2018/7/19 11:34
 */

public class ConnectThread implements Runnable {
    private Socket socket;

    public ConnectThread(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        Socket redisSocket = null;
        InputStream redisInput = null;
        OutputStream redisOutput = null;
        try {
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
            redisSocket = new Socket("192.168.0.27", 6379);
            redisInput = redisSocket.getInputStream();
            redisOutput = redisSocket.getOutputStream();

            byte[] data = new byte[1024];
            byte[] redisData = new byte[1024];
            int length;
//            while ( 0 != inputStream.available() && -1 != (length = inputStream.read(data))) {
//                System.out.println("send:" + new String(data));
//                redisOutput.write(data, 0, length);
//                length = redisInput.read(redisData);
//                outputStream.write(redisData, 0, length);
//                System.out.println("receive:" + new String(redisData));
//                //outputStream.write("+OK\r\n".getBytes());
//            }
            while(true) {
                if(inputStream.available()>0) {
                    if(-1 == (length = inputStream.read(data))) break;
                    System.out.println("send:" + new String(data));
                    redisOutput.write(data, 0, length);
                    length = redisInput.read(redisData);
                    outputStream.write(redisData, 0, length);
                    outputStream.flush();
                    System.out.println("receive:" + new String(redisData));
                    //outputStream.write("+OK\r\n".getBytes());
                }
//                else if(inputStream.available()==0){
//                    System.out.println("连接中断");
//                    break;
//                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) inputStream.close();
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
                socket.close();
                if (redisInput != null) redisInput.close();
                if (redisOutput != null) {
                    redisOutput.flush();
                    redisOutput.close();
                }
                if (redisSocket != null) redisSocket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("exit-------------");
        }

    }
}
